import React, { useState, useEffect, useRef } from 'react';
import { Button, Tabs, Form, message, Select } from 'antd';
import { connect } from 'umi';
import { TjContent, TjUpload } from '@/tjComponents';
import { UploadOutlined } from '@ant-design/icons';
import { columns } from './helper';
import { arrToFormData, formDataToArr } from '@/utils/editorTable';
import { useForm } from 'antd/es/form/Form';
import { HttpCode } from '#/utils/contacts.js';
// ts-ignore
import {
  getNxTradeSequence,
  getNxList,
  saveNxList,
  nxImportUrl,
  nxDownloadTemplateUrl,
  exportNxData,
} from '../services.js';
import moment from 'moment';
import { downloadFileForFront } from '@/tjComponents/TjUpload/TjUploadContent';
import TjTable from '@/pages/ETrade/components/TjTable';
import './index.less';

const NxMain: React.FC<INxMainProps> = (props) => {
  const [tabList, setTabList] = useState<any[]>([]);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [tabActiveKey, setTabActiveKey] = useState<string>();
  const [forecastDate, setForecastDate] = useState<string>();
  const [importStations, setImportStations] = useState<any[]>([]);
  const [importStationVal, setImportStationVal] = useState<string>();
  const isEdit = useRef<boolean>(false);
  const [form] = useForm();

  const changeLoading = (type: boolean) => {
    setLoading(type);
    props.dispatch({
      type: 'dayRollingTradeStragety/setHeaderLoading',
      payload: type,
    });
  };

  const getTabs = () => {
    const params = {
      forecastDate: moment(props.tradeDate).format('YYYY-MM-DD'),
      marketId: props.marketId,
      stationId: props.stationId,
    };
    setTabActiveKey(undefined);
    setForecastDate(undefined);
    // setLoading(true);
    changeLoading(true);
    getNxTradeSequence(params)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          if (res.data.length > 0) {
            setTabList(res.data);
            setTabActiveKey(res.data[0].tradeSequenceId);
            setForecastDate(res.data[0].forecastDate);
            setDataSource([]);
            form.resetFields();
          } else {
            setTabList([]);
            setTabActiveKey(undefined);
            setDataSource([]);
            form.resetFields();
            setLoading(false);
          }
        } else {
          // setLoading(false);
          changeLoading(false);
          message.error(res.message);
        }
      })
      .catch(() => {
        // setLoading(false);
        changeLoading(false);
      });
  };

  const query = () => {
    getNxList({
      forecastDate,
      marketId: props.marketId,
      stationId: props.stationId,
      tradeSequenceId: tabActiveKey,
      queryDate: moment(props.tradeDate).format('YYYY-MM-DD'),
    })
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          if (res.data.length > 0) {
            const formData = arrToFormData(res.data, 'tableId', [
              'declareType',
              'declarePrice',
              'declareQuantity',
            ]);
            form.setFieldsValue(formData);
            setDataSource(res.data);
          }
        } else {
          message.error(res.message);
          setDataSource([]);
          form.resetFields();
        }
      })
      .finally(() => {
        // setLoading(false);
        changeLoading(false);
      });
  };

  const uploadSuccessCb = () => {
    if (forecastDate) {
      query();
    }
  };

  const exportData = () => {
    if (dataSource.length === 0) {
      message.warning('暂无导出数据');
      return;
    }
    setLoading(true);
    exportNxData({
      forecastDate: moment(forecastDate).format('YYYY-MM-DD'),
      marketId: props.marketId,
      stationId: props.stationId,
      tradeSequenceId: tabActiveKey,
      queryDate: moment(props.tradeDate).format('YYYY-MM-DD'),
    })
      .then((res: any) => {
        if (res) {
          downloadFileForFront(res, `宁夏短期交易决策_${moment().format('YYYY-MM-DD')}.xlsx`);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const changeTab = (val: string) => {
    const item = tabList.find((v) => v.tradeSequenceId === val);
    if (item) {
      setTabActiveKey(val);
      setForecastDate(item.forecastDate);
    }
  };

  const save = () => {
    setLoading(true);
    const formData = form.getFieldsValue();
    const arr = formDataToArr(formData, dataSource, 'tableId');
    saveNxList(arr)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          message.success('保存成功');
          query();
        } else {
          message.error(res.message);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const onValuesChange = (changedValues: any) => {
    if (changedValues) {
      isEdit.current = true;
    }
  };

  useEffect(() => {
    if (props.nxRefresh) {
      getTabs();
    }
  }, [props.nxRefresh]);

  useEffect(() => {
    if (forecastDate) {
      query();
    }
  }, [forecastDate]);

  useEffect(() => {
    if (props.originStations && props.originStations.length > 0) {
      const item = props.originStations.find((v) => v.stationId === '64043004');
      if (item) {
        setImportStations([
          {
            label: item.stationName,
            value: item.stationId,
          },
        ]);
        setImportStationVal(item.stationId);
      }
    }
  }, []);

  return (
    <div className="nx-main">
      <TjContent className="content">
        <Tabs
          tabBarExtraContent={{
            right: (
              <div className="nx-options">
                {dataSource.length > 0 && (
                  <Button
                    type="primary"
                    onClick={save}
                    loading={loading}
                    disabled={
                      moment().startOf('day').isAfter(moment(props.tradeDate).startOf('day')) &&
                      !isEdit.current
                    }
                  >
                    保存
                  </Button>
                )}
                {dataSource.length > 0 && (
                  <Button
                    type="link"
                    icon={<UploadOutlined />}
                    loading={loading}
                    onClick={exportData}
                  >
                    导出
                  </Button>
                )}
                <TjUpload
                  uploadUrl={nxImportUrl}
                  uploadSuccessCb={uploadSuccessCb}
                  loading={loading}
                  accept=".xls,.xlsx"
                  hearder={
                    <Select
                      options={importStations}
                      value={importStationVal}
                      style={{ marginBottom: 16 }}
                    />
                  }
                  uploadOtherParams={{
                    stationId: importStationVal,
                  }}
                  downloadTemplate={{
                    url: nxDownloadTemplateUrl,
                    templateName: '功率预测导入模板.xlsx',
                  }}
                />
              </div>
            ),
          }}
          activeKey={tabActiveKey}
          onChange={changeTab}
        >
          {tabList.map((item) => {
            return <Tabs.TabPane tab={item.tradeSequenceName} key={item.tradeSequenceId} />;
          })}
        </Tabs>
        <Form form={form} className="table-box" onValuesChange={onValuesChange}>
          <TjTable
            columns={columns(
              moment().startOf('day').isAfter(moment(props.tradeDate).startOf('day')),
            )}
            dataSource={dataSource}
            primaryKey="tableId"
            isLoading={loading}
          />
        </Form>
      </TjContent>
    </div>
  );
};

interface INxMainProps {
  marketId: string;
  stationId: string;
  tradeDate: string;
  nxRefresh?: string;
  stations?: any[];
  originStations?: any[];
  dispatch?: any;
}

export default connect(({ dayRollingTradeStragety }: any) => ({
  stationId: dayRollingTradeStragety.stationId,
  marketId: dayRollingTradeStragety.marketId,
  tradeDate: dayRollingTradeStragety.tradeDate,
  nxRefresh: dayRollingTradeStragety.nxRefresh,
  stations: dayRollingTradeStragety.stations,
  originStations: dayRollingTradeStragety.originStations,
}))(NxMain);
